#include "Temperature_logger.h"

char String_Lcd[10] = "HELLO";

volatile unsigned int KEY_PRESS_DURATION_COUNT = 0;
volatile unsigned char KEY_PRESSED = KEY_INVALID ;
volatile unsigned char PRESENT_KEY = KEY_INVALID;
volatile char VALID_KEY_PRESSED = KEY_INVALID;



extern Main_State Curr_State;
extern Main_State Prev_State;
extern Main_State Next_State;

extern LCD_State Curr_LCD_State;
extern LCD_State Next_LCD_State;

volatile char Logging_Trigger=0;	//
volatile char First_Log_Flag = 0;
Press_State PressDuration;


void delay_ds(unsigned char ds)
{

#ifndef SIMULATION
	uint16_t i, lim= 10*ds;
	for(i=0; i<lim; i++)
	{
		uint16_t __ticks = F_CPU / 400;
		__asm__ volatile (
			"1: sbiw %0,1" "\n\t"
			"brne 1b"
			: "=w" (__ticks)
			: "0" (__ticks)
		);
	}
#endif

}

int main(void)
{
//Initililise all that is required!!!



	RTC_init();

    LCD_Init(); 
  
    LCD_Clear();
	
	Enable_Joystick();
	
	DF_SPI_init();
	
	DF_Page0_init();	// CAREFUL....EVERYTIME DEVICE IS RESET, ALL DATA IS LOST AS DATAPOINTERS ARE REINITIALIZED!!!! NEED FIX BY USING SIGNATURE
	
	Ena_Key_Press_Dur_Count();
   
    LCD_puts(String_Lcd);
	
	delay_ds(5);


// Execute below loop when only the Auto Power off duration is not expired. 
// Else, shutdown execution and wait for only user keyboard interrupt to become alive.
// This may require to identify if power save mode is ON-OFF.
// When Power Save mode is enabled, all system shutdown and Microcontroller to go into sleep mode.
// Must become alive when interrupt on pin change occurs. If RTC interrupt happens, update clock variables,
// and go to sleep again...

while (1)
{	
	if (KEY_PRESS_DURATION_COUNT>LONG_PRESS_DURATION)
		{	PressDuration = Long_Press;
		}
	else 
		{PressDuration = Short_Press;
		}
 
	LCD_Menu_Control(PRESENT_KEY,PressDuration,Curr_State);
	
	LCD_Process(Next_LCD_State,Curr_State);

	delay_ds(1);
	
	Curr_LCD_State = Next_LCD_State;
	
	Main_Menu_Control(VALID_KEY_PRESSED,PressDuration,Curr_LCD_State);
	
	if(Next_State!=Curr_State)
	
	Menu_Process(Next_State,Curr_LCD_State);
	
	VALID_KEY_PRESSED=KEY_INVALID;	
	
	delay_ds(1);	

	Curr_State = Next_State;
	
//	Flash_SPI_Check();	// THIS FUNCTION WHEN FAILS TO READ PROPER FLASH ID WILL HANG THE SYSTEM.
	
	Store_Log_Flash();	// This function will store the current temp in the dflash based on conditions...
	
}	

return 0;
}
